package com.xdwanj.criminalintent.viewmodel;

import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;

import com.xdwanj.criminalintent.pojo.Crime;
import com.xdwanj.criminalintent.repository.CrimeRepository;

import java.util.UUID;

public class CrimeDetailViewModel extends ViewModel {

    private final CrimeRepository crimeRepository = CrimeRepository.get();

    //这个就是crimeLiveData对象观察的对象,如果这个数据被修改了,就会触发Transformations.switchMap()方法
    private final MutableLiveData<UUID> crimeIdLiveData = new MutableLiveData<>();

    public LiveData<Crime> crimeLiveData = Transformations.switchMap(
            crimeIdLiveData, //被观察的对象
            new Function<UUID, LiveData<Crime>>() {
                @Override
                public LiveData<Crime> apply(UUID crimeId) {
                    return crimeRepository.getCrime(crimeId);
                }
            }
    );

    /**
     * 传入CrimeId, 内部通过CrimeRepository获取Crime对象
     *
     * @param crimeId crime的id
     */
    public void loadCrime(UUID crimeId) {
        crimeIdLiveData.setValue(crimeId);
    }

    public void saveCrime(Crime crime) {
        crimeRepository.updateCrime(crime);
    }

    public CrimeDetailViewModel() {
        super();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
    }
}
